package common;

import java.io.PrintStream;
import java.util.ArrayList;



public class LogPrinter {
	private ArrayList<String> infos = new ArrayList<String>();
	private PrintStream writer = null;

	/**
	 * Initial print stream by given writer
	 * @param writer
	 */
	public LogPrinter( PrintStream writer ){
		this.writer = writer;
	}
	
	/**
	 * store info to print until user codes comes
	 * @param info
	 * @param lineNum
	 */
	public void printTrace( String info, int lineNum ){
		infos.add( String.format("\t%d: %s", lineNum, info ) );		
	}
	
	/**
	 * print user code and stored infos
	 * @param inputCode
	 * @param lineNum
	 */
	public void printInputCode( String inputCode, int lineNum ){
		String line = String.valueOf( lineNum );		
		if( inputCode.length()>0 && inputCode.charAt( inputCode.length()-1 ) != '\n' ){
			inputCode+='\n';
		}
		
		writer.print( line + ":" + inputCode );		

		for( String info: infos ){			
			writer.println( info );
		}
		infos.clear();
	}
	
	/**
	 * print string to log
	 * @param s
	 */
	public void println(String s){
		writer.print(s+'\n');
	}

	/**
	 * close writer
	 */
	public void close(){
		writer.flush();
		writer.close();
	}
}
